<script setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'

import { getFieldsApi, getTableListApi, saveTableListApi, getSourceListApi } from '@/service/db.js'
const sourceList = ref([])

let selectedFields = []
const drawerTitle = ref('设置列表项')

const fieldList = reactive([])
const ruleForm = ref({
  table: '',
  fields: []
});

// Add table reference
const fieldTableRef = ref(null);
const rules = ref({

});

// 当前选中的行
const selectedRows = ref([]);

// 获取数据源配置
const getListConfig = (table) => {
  getTableListApi({ table }).then(({ code, data }) => {
    if (code !== 200) {
      return
    }
    // data fields 给

    ruleForm.value = data
    // fieldTableRef 设置选中， element-plus 的 table 组件没有 setSelection 方法
    nextTick(() => {
      let keys = data.items.map(item => item.Field)
      let keyMap = data.items.reduce((acc, item) => {
        acc[item.Field] = item
        return acc
      }, {})

      fieldList.forEach(row => {
        if (keys.includes(row.Field)) {
          row.Width = keyMap[row.Field].Width
          row.Title = keyMap[row.Field].Title
          row.Comment = keyMap[row.Field].Comment
          row.Alias = keyMap[row.Field].Alias ? keyMap[row.Field].Alias : ''
          row.Source = keyMap[row.Field].Source ? keyMap[row.Field].Source : ''
          fieldTableRef.value.toggleRowSelection(row, true);
        }
      });
    });

  })
}

// 获取表的字段
const getFields = (table) => {
  getFieldsApi({ table }).then(({ data }) => {
    // 初始化data中不存在的字段，如Width
    data.forEach(item => {
      item.Width = 100
      item.Title = item.Comment
      // 设置别名
      item.Alias = ''
      // 设置对应得数据源映射
      item.Source = ''
    })

    // data to fieldList
    fieldList.length = 0
    fieldList.push(...data)
    console.log(data)
    // 调用配置
    getListConfig(table)
  })
}

const emit = defineEmits(['fetch-list'])

const ruleFormRef = ref(null);
const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      let data = {};
      data.table = table.value;
      data.title = ruleForm.value.title;
      // 获取fieldList中selectedFields的Field,Width,Title
      data.fields = fieldList.filter(item => selectedFields.includes(item.Field)).map(item => ({
        Field: item.Field,
        Width: item.Width,
        Title: item.Title,
        Alias: item.Alias,
        Source: item.Source
      }));

      saveTableListApi(data).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: '提交成功',
            type: 'success'
          });
          closeDrawer();
          emit('fetch-list')
        } else {
          ElMessage({
            message: '提交失败',
            type: 'error'
          });
        }
      });
    } else {
      ElMessage({
        message: '提交失败',
        type: 'error'
      });
      return false;
    }
  });
}

const resetForm = () => {
  ruleFormRef.value.resetFields();
  // 重置选中
  selectedFields = []
  selectedRows.value = []
  fieldTableRef.value.clearSelection()
}

const table = ref('')
const drawerVisible = ref(false)
const openDrawer = (row) => {
  table.value = row.name;
  drawerTitle.value = `设置列表项 - ${table.value}`
  drawerVisible.value = true;

  getFields(table.value)

  // 重置表单
  ruleForm.value = {
    table: table.value,
    fields: []
  }
}
const closeDrawer = () => {
  drawerVisible.value = false;
}

// 选择字段
const handleSelectionChange = (val) => {
  // 将当前Field存入selectedFields
  selectedFields.push(...val.map(item => item.Field))
}



// 获取数据源
const dialogVisible = ref(false);

const getSourceList = () => {
  getSourceListApi().then(({ data }) => {
    sourceList.value = data;
  })
}

// 设置字段
const fieldForm = ref({
  Field: '',
  Title: '',
  Width: '',
  Comment: '',
  Alias: '',
  Source: ''
});

const fieldFormRef = ref(null)
const showEditDialog = (row) => {

  fieldForm.value = row;
  dialogVisible.value = true;
  getSourceList();
}

const closeSourceDialog = () => {
  dialogVisible.value = false;
  fieldForm.value = {
    Field: '',
    Title: '',
    Width: '',
    Comment: '',
    Alias: '',
    Source: ''
  }
}

const submitFieldForm = () => {
  // 同步到选中的字段中
  // 在fieldList中找到对应的字段并更新
  const index = fieldList.findIndex(item => item.Field === fieldForm.value.Field);
  if (index !== -1) {
    // 更新字段信息
    fieldList[index].Title = fieldForm.value.Title;
    fieldList[index].Width = fieldForm.value.Width;
    fieldList[index].Comment = fieldForm.value.Comment;
    fieldList[index].Alias = fieldForm.value.Alias;
    fieldList[index].Source = fieldForm.value.Source;

    // 如果该字段已被选中，确保更新后的数据会被提交
    if (selectedFields.includes(fieldForm.value.Field)) {
      // 已经在选中列表中，不需要额外操作
    } else {
      // 如果字段未被选中，添加到选中列表并更新表格选择状态
      selectedFields.push(fieldForm.value.Field);
      fieldTableRef.value.toggleRowSelection(fieldList[index], true);
    }

    ElMessage({
      message: '字段设置已更新',
      type: 'success'
    });
  } else {
    ElMessage({
      message: '未找到对应字段',
      type: 'warning'
    });
  }


  closeSourceDialog()
}


defineExpose({
  openDrawer,
  closeDrawer
});

</script>

<template>
  <el-drawer :title="drawerTitle" v-model="drawerVisible" size="100%">
    <div class="container">
      <div class="form">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :inline="true" label-position="left">
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleFormRef')">保存</el-button>
            <el-button @click="resetForm('ruleFormRef')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="field-list">
        <el-table ref="fieldTableRef" :data="fieldList" border @selection-change="handleSelectionChange"
          row-key="Field">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="Field" label="字段"></el-table-column>
          <el-table-column prop="Title" label="标题"></el-table-column>
          <el-table-column prop="Width" label="宽度"></el-table-column>
          <el-table-column prop="Comment" label="描述"></el-table-column>
          <el-table-column prop="Alias" label="别名"></el-table-column>
          <el-table-column prop="Source" label="数据源"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button type="primary" @click="showEditDialog(row)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog title="设置字段" v-model="dialogVisible" append-to-body size="30%">
      <el-form ref="fieldFormRef" :model="fieldForm" label-position="top">
        <el-form-item label="字段">
          <el-input v-model="fieldForm.Field" disabled></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="fieldForm.Title"></el-input>
        </el-form-item>
        <el-form-item label="宽度">
          <el-input v-model="fieldForm.Width"></el-input>
        </el-form-item>

        <el-form-item label="别名">
          <el-input v-model="fieldForm.Alias"></el-input>
        </el-form-item>

        <el-form-item label="数据源">
          <el-select v-model="fieldForm.Source" placeholder="请选择数据源">
            <el-option v-for="item in sourceList" :key="item.table" :label="item.title" :value="item.table">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitFieldForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </el-drawer>
</template>

<style scoped lang="less">
.flex {
  display: flex;
  justify-content: space-between;

  .btn {
    cursor: pointer;
  }
}

.flex.tip {
  color: #409eff;
  font-weight: bold;
}
</style>
